﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Syngine.Components.Animations
{
	public class SpriteSheetAnimation : Animation
	{
		public SpriteSheetAnimation(Texture2D texture, Vector2 frames, int frameWidth, int frameHeight) : this(texture, frames, frameWidth, frameHeight, 1.0f, 0, 1)
		{
		}

		public SpriteSheetAnimation(Texture2D texture, Vector2 frames, int frameWidth, int frameHeight, float duration, int startFrame, int endFrame)
		{
			Texture = texture;
			Frames = frames;
			Duration = duration;
			FrameWidth = frameWidth;
			FrameHeight = frameHeight;
			CurrentFrame = startFrame;
			StartFrame = startFrame;
			EndFrame = endFrame;
			StepDuration = duration / (endFrame - startFrame);
		}

		public int StartFrame { get; set; }

		public int EndFrame { get; set; }

		public int FrameWidth { get; private set; }

		public int FrameHeight { get; private set; }

		public Vector2 Frames { get; private set; }

		public int CurrentFrame { get; private set; }

		public float StepDuration { get; private set; }

		public override void LoadContent(LoadContext context)
		{
			Origin = new Vector2(FrameWidth / 2, FrameHeight / 2);
			Bounds = new Rectangle(CurrentFrame * FrameWidth, (int)Frames.Y * FrameHeight, FrameWidth, FrameHeight);
		}

		public override void UnloadContent()
		{
		}

		protected override void UpdateCore(UpdateContext context)
		{
			if (State == PlayableState.Playing)
			{
				DurationTimer += (float)context.GameTime.ElapsedGameTime.TotalSeconds;

				if (DurationTimer >= StepDuration)
				{
					DurationTimer -= StepDuration;

					if (++CurrentFrame > EndFrame)
					{
						CurrentFrame = StartFrame;
					}
				}
			}

			SourceRectangle = new Rectangle(CurrentFrame * FrameWidth, (int)Frames.Y * FrameHeight, FrameWidth, FrameHeight);

			base.UpdateCore(context);
		}

		protected override void DrawCore(DrawContext context)
		{
			if (State != PlayableState.Stopped)
			{
				base.DrawCore(context);
				//context.Draw(Texture, Position, Bounds, Color, Rotation, Origin, Scale, Effects, Depth);
			}
		}
	}
}
